package cn.ailearn.security.service;

import cn.ailearn.module.mapper.PermissionsMapper;
import cn.ailearn.module.mapper.UsersMapper;
import cn.ailearn.module.pojo.entity.Users;
import cn.ailearn.security.details.MySysUserDetails;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @ClassName MyUserDetailsService
 * @Description 提供查询用户功能，如根据用户名查询用户，并返回UserDetails
 * @Author WDEMO
 * @Date 2025/10/22 18:11
 */

@Slf4j
@Component
@RequiredArgsConstructor
public class MyUserDetailsService implements UserDetailsService {

    private final UsersMapper usersMapper;
    private final PermissionsMapper permissionsMapper;



    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("根据用户名查询用户信息");
        Users user = getUserByUsername(username);
        if(ObjectUtil.isNull(user)){
            throw new UsernameNotFoundException("用户名不存在");
        }
        // 查询用户的权限码
        Set<String> permissionCodes = permissionsMapper.selectByPermissionCode(user.getId());

        return new MySysUserDetails(user,permissionCodes);
    }


    private Users getUserByUsername(String username){
        LambdaQueryWrapper<Users> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Users::getUsername,username);
        return usersMapper.selectOne(lambdaQueryWrapper);
    }
}
